#!/bin/bash

# the following environment variables must be set
: ${ROOT_DIR?} ${BUILD_DIR?} ${PACKAGE_LBL?} ${PACKAGE_DIR?} ${PACKAGE_NAME?} ${PACKAGE_SEP?}

# more variables
APP_PATH="${BUILD_DIR}/openpilotgcs_release/bin/OpenPilot GCS.app"
TEMP_FILE="${PACKAGE_DIR}/OpenPilot-temp.dmg"
OUT_FILE="${PACKAGE_DIR}/../${PACKAGE_NAME}${PACKAGE_SEP}${PACKAGE_LBL}${PACKAGE_SEP}osx.dmg"
VOL_NAME="OpenPilot"

# prepare the stage
rm -f "${TEMP_FILE}"
rm -f "${OUT_FILE}"

# if an OpenPilot volume is already mounted, unmount it
if [ -f "/Volumes/${VOL_NAME}" ]
then
echo "Unmount existing /Volumes/${VOL_NAME}"
hdiutil unmount "/Volumes/${VOL_NAME}"
fi

hdiutil convert "${ROOT_DIR}/package/osx/OpenPilot.dmg" \
    -format UDRW -o "${TEMP_FILE}"
device=$(hdiutil attach "${TEMP_FILE}" | \
    egrep '^/dev/' | sed 1q | awk '{print $1}')

#Just in case something is still mounted as ${VOL_NAME}, check the correct mount point
mountvolume=$(hdiutil info | egrep "^${device}"| egrep "${VOL_NAME}" | sed 's/.*Volumes\///;s/*//' | sed 1q)

echo "Image mounted as /Volumes/${mountvolume}"

if [ ! -d "/Volumes/${mountvolume}/OpenPilot GCS.app" ]
then
    echo "Cannot find a valid image at /Volumes/${mountvolume}"
    exit 1
fi

# packaging goes here
cp -a "${APP_PATH}" "/Volumes/${mountvolume}"

cp "${BUILD_DIR}/uavobject-synthetics/matlab/OPLogConvert.m" "/Volumes/${mountvolume}/Utilities"
cp "${ROOT_DIR}/WHATSNEW.txt" "/Volumes/${mountvolume}"
cp "${ROOT_DIR}/README.txt" "/Volumes/${mountvolume}/Docs"
cp "${ROOT_DIR}/MILESTONES.txt" "/Volumes/${mountvolume}/Docs"
cp "${ROOT_DIR}/LICENSE.txt" "/Volumes/${mountvolume}/Docs"
cp "${ROOT_DIR}/GPLv3.txt" "/Volumes/${mountvolume}/Docs"

"${ROOT_DIR}/package/osx/libraries" \
    "/Volumes/${mountvolume}/OpenPilot GCS.app" || exit 1

hdiutil detach ${device}

min=`hdiutil resize ${TEMP_FILE} | awk \{print\ \$\1\}`
echo "Resizing dmg to ${min}"

hdiutil resize -sectors ${min} ${TEMP_FILE}
hdiutil convert "${TEMP_FILE}" -format UDZO -o "${OUT_FILE}"

# cleanup
rm "${TEMP_FILE}"
